﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;

namespace BeniSurvivoraGoturKocum
{
    class Program
    {
        //static CookieContainer cookies = null;

        static void Main(string[] args)
        {

            var cookies = Login();


            var target = 0;
            var score = 0;
            var max = 0;

            if (args.Length == 1)
            {
                target = int.Parse(args[0]) - 1;
                
            }

            for (; ; )
            {
                try
                {
                    if (target == 0)
                    {
                        Console.Write("Specify target: "); target = int.Parse(Console.ReadLine());
                        if (target < 0) target = 1;
                    }
                    else
                        Console.WriteLine("Target increased: {0}", target);

                    Console.Write("Game Progress: ");

                    for (; score < target; )
                    {

                        System.Windows.Forms.Application.DoEvents();
                        var success = Play(cookies);

                        if (success)
                        {
                            Console.Clear();
                            Console.Write("Game Score: {0}", ++score);
                            //Score++;
                        }
                        else
                        {
                            score = 0;
                            Console.WriteLine("Fail!!!");

                        }

                        if (score <= max) continue;

                        max = score;
                        Console.Title = target + ", " + max + " - " + DateTime.Now;
                    }

                    Save(cookies);

                    target += 3;
                    max = 0;
                    score = 0;

                }
                catch(Exception ex)
                {
                    Console.WriteLine();
                    Console.WriteLine("Error!");

                    Console.WriteLine();
                    Console.WriteLine(ex.ToString());

                    System.Diagnostics.Process.Start(System.Windows.Forms.Application.ExecutablePath, target.ToString());
                    //Console.ReadLine();
                    return;
                }
            }
        }

        private static void Save(CookieContainer cookies)
        {
            var url = @"http://www.acunn.com/oyun/game1of3?save=1";

            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.CookieContainer = cookies;
            request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
            request.ContentType = @"application/x-www-form-urlencoded";
            request.ContentLength = 0;
            request.Method = "POST";
            request.Referer = @"http://www.acunn.com/oyun/game3of4";
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.AllowAutoRedirect = false;
            request.Timeout = 1000 * 60 * 60;

            request.GetRequestStream().Close();


            var response = request.GetResponse();
            var stream = response.GetResponseStream();

            if (stream != null)
            {
                var sr = new System.IO.StreamReader(stream);
                var s = sr.ReadToEnd();

                stream.Close();
            }

            
        }

        private static bool Play(CookieContainer cookies)
        {
            var url = @"http://www.acunn.com/oyun/game1of3?res=";

            var r = new Random();

            url += (r.Next(3) + 1).ToString();

            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.CookieContainer = cookies;
            request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
            request.ContentType = @"application/x-www-form-urlencoded";
            request.ContentLength =0;
            request.Method = "POST";
            request.Referer = @"http://www.acunn.com/oyun/game3of4";
            request.Headers.Add( "X-Requested-With", "XMLHttpRequest");
            request.AllowAutoRedirect = false;

            request.Timeout = 1000 * 60 * 60;
            request.GetRequestStream().Close();

            
            var response = request.GetResponse();
            StreamReader sr;
            using (var stream = response.GetResponseStream())
            {
                if (stream == null) return false;

                sr = new StreamReader(stream);
                var s = sr.ReadToEnd();

                return s.Contains("true");
            }
            
        }


        private static CookieContainer Login()
        {
            var cookies = new CookieContainer();

            const string url = @"http://www.acunn.com/uye/giris";
            string 
                username = "",
                password = "";

            Console.Write("Username: "); username = Console.ReadLine();
            Console.Write("Password: "); password = Console.ReadLine();
            Console.WriteLine();
            Console.WriteLine("Loging in...");

            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.CookieContainer = cookies;

            request.Timeout = 1000 * 60;

            var response = (HttpWebResponse)request.GetResponse();
            cookies = new CookieContainer();
            cookies.Add(response.Cookies);

            string data = "username=" + username + "&password=" + password + "&redirect_to=" + System.Web.HttpUtility.UrlEncode("/oyun/game3of4") + "&remember_me=y";
            byte[] bits = Encoding.UTF8.GetBytes(data);

            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.CookieContainer = cookies;
            request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";

            request.ContentType = @"application/x-www-form-urlencoded";
            request.ContentLength = bits.Length;
            request.Method = "POST";
            request.UserAgent = @"Mozilla (StealhED (R))";

            request.Timeout = 1000 * 60 * 60;
            using (var st = request.GetRequestStream())
            {
                st.Write(bits, 0, bits.Length);
                st.Close();

                response = (HttpWebResponse)request.GetResponse();
                //response.GetResponseStream().Close();
            }

            response.Close();

            Console.WriteLine("Logged in.");
            return cookies;
        }
    }
}
